from django import template
from page.models import Page
from test.models import Test
from django.core.cache import cache
from page.tree_utils import get_root

register = template.Library()

def page_tree():
    root = get_root()
    if root is not None:
        return "<ol>"+tree_traversal(add_div, add_ol, root)+"</ol>"
    else:
        return "There are no pages"

def page_tree_navigation():
    tree = cache.get('tree_navigation')
    #If the tree is cashed
    #tree = None
    if tree is not None:
        print "cache"
        return tree
    #Create a new tree
    else:
        tree = "<ul id='tree-navigation' class='nav nav-list'>"+tree_traversal(generate_link, add_ul, get_root())+"</ul>"
        #Temp timeout value 24h
        cache.set('tree_navigation', tree, 60*60*24)
        return tree

def tree_traversal(list_content, list_type, page):
    if page.child is not None and page.sibling is not None: 
        return generate_li_head(page)+list_content(page)+list_type(tree_traversal(list_content, list_type, page.child))+"</li>"+tree_traversal(list_content, list_type, page.sibling)
    elif page.child is not None: 
        return generate_li_head(page)+list_content(page)+list_type(tree_traversal(list_content, list_type, page.child))+"</li>"
    elif page.sibling is not None:
        return generate_li_head(page)+list_content(page)+"</li>"+tree_traversal(list_content, list_type, page.sibling)
    else:
        return generate_li_head(page)+list_content(page)+"</li>"
    
def generate_li_head(page):
    page_id = str(page.id)
    if page.type() == Test:
        return '<li id="page_'+page_id+'" class="test">'
    else:
        return '<li id="page_'+page_id+'" class="page">'

def add_div(page):
    return "<div>"+page.title+"<i class='page-trash icon-trash pull-right'></i></div>"

def add_ul(text):
    return "<ul>"+text+"</ul>"

def add_ol(text):
    return "<ol>"+text+"</ol>"

def generate_link(page):
        return "<a href='"+page.get_absolute_url()+"'>"+page.title+"</a>"
    

register.simple_tag(page_tree)
register.simple_tag(page_tree_navigation)